package com.yxx.sys.controller;

import com.yxx.sys.common.ActiverUser;
import com.yxx.sys.common.Result;
import com.yxx.sys.common.WebUtils;
import com.yxx.sys.domain.Loginfo;
import com.yxx.sys.service.LoginfoService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 21:54 2020/8/12
 **/
@RestController
@RequestMapping("login")
public class LoginController {

  @Autowired
  LoginfoService loginfoService;

  @PostMapping("login")
  @ApiOperation(value="登录接口", notes="用户名登录")
  public Result login(String loginname,String pwd){
    Subject subject = SecurityUtils.getSubject();
    AuthenticationToken token = new UsernamePasswordToken(loginname,pwd);
    try{
      subject.login(token);
      ActiverUser activeUser = (ActiverUser) subject.getPrincipal(); //这里拿出来的ActiverUser就是UserRealm认证时候我们自己创建的
      WebUtils.getSession().setAttribute("user",activeUser.getUser());

      //添加登录日志
      Loginfo entity = new Loginfo();
      entity.setLoginname(activeUser.getUser().getName()+"-"+activeUser.getUser().getLoginname());
      entity.setLoginip(WebUtils.getRequest().getRemoteAddr());//ip
      entity.setLogintime(LocalDateTime.now());
      loginfoService.save(entity);

  return Result.LOGIN_SUCCESS;
    }catch(AuthenticationException e){
      e.printStackTrace();
      return Result.LOGIN_ERROR_PASS;
    }
  }
}
